﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Server.Data {
    public class BaseDAO : IDisposable {
        protected Database _db = null;

        public BaseDAO() {
            _db = DatabaseFactory.CreateDatabase("MainDB");
            if (_db == null) {
                //LogHelper.WriteError("创建数据库对象失败", LogCatagory.CM);
                throw new Exception("创建数据库对象失败");
            }
        }

        public void Dispose() {
            if (_db != null) {
                _db = null;
            }
        }

        protected object ExecuteSqlScalar(string pSqlText) {
            return _db.ExecuteScalar(System.Data.CommandType.Text, pSqlText);
        }

        protected object ExecuteScalar(string pSPName, params object[] pParms) {
            DbCommand command = _db.GetStoredProcCommand(pSPName, pParms);
            return _db.ExecuteScalar(command);
        }

        protected int ExecuteNonQuery(string pSPName, params object[] pParms) {
            DbCommand command = _db.GetStoredProcCommand(pSPName, pParms);
            return _db.ExecuteNonQuery(command);
        }

        protected DataSet ExecuteDataSet(string pSPName, params object[] pParms) {
            return _db.ExecuteDataSet(pSPName, pParms);
        }

        /// <summary>
        /// 执行SQL语句，返回DataSet第一张表
        /// </summary>
        /// <param name="pSql"></param>
        /// <param name="pParms"></param>
        /// <returns></returns>
        protected DataTable ExecuteSqlDataTable(string pSql) {
            DataTable ret = null;
            DataSet ds = _db.ExecuteDataSet(CommandType.Text, pSql);
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0) {
                ret = ds.Tables[0];
            }

            return ret;
        }
        /// <summary>
        /// 返回DataTable，返回DataSet的第一个表
        /// </summary>
        /// <param name="pSPName"></param>
        /// <param name="pParms"></param>
        /// <returns></returns>
        protected DataTable ExecuteDataTable(string pSPName, params object[] pParms) {
            DataTable ret = null;
            DataSet ds = _db.ExecuteDataSet(pSPName, pParms);
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0) {
                ret = ds.Tables[0];
            }

            return ret;
        }
    }
}
